package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.*;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE = 1;//主图引用
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserService wmUserService;

    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if (dto.getKeyword() != null && dto.getKeyword() != "") {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        Page page = new Page(dto.getPage(), dto.getSize());

        IPage result = page(page, lambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 发布文章业务处理
     *
     * @param dto
     * @param isSubmit 0：草稿  1：提交
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {

        //1:校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (isSubmit == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //2:解析json --》wmnews  保存wmnews表
        WmNews wmNews = new WmNews();
        //2.1 对象浅拷贝 从哪源头copy 那里目标
        BeanUtils.copyProperties(dto, wmNews);
        //2.2: 封面是自动，那就type赋值为null
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //2.3：处理解析封面图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String s = dto.getImages().toString().replace("[", "").replace("]", "")
                    .replace(fileServerUrl, "").replace(" ", "");
            wmNews.setImages(s);
        }
        //2.4:保存新闻表
        wmNews.setCreatedTime(new Date());
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wmNews.setUserId(user.getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            this.updateById(wmNews);
            //把素材与文章关系表关系删除   先删后新增
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
        }


        //3:素材表  替换 解析   保存素材表
        String content = dto.getContent();
        //3.1 json转换为list集合
        List<Map> imageList = JSON.parseArray(content, Map.class);
        //3.2: 提取内容中图片
        List<String> ectractUrlInfo = this.ectractUrlInfo(imageList);


        //4: 批量保存关系表
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode()) && ectractUrlInfo.size() > 0) {

            //调用保存文章和素材关系表
            ResponseResult result = this.saveRelativeInfoForContent(ectractUrlInfo, wmNews.getId());
            if (result.getCode() != 0) {
                return result;
            }
        }

        //5:设置封面
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode())) {
            ResponseResult result = this.saveRelativeInfoForCover(dto, ectractUrlInfo, wmNews);
            if (result.getCode() != 0) {
                return result;
            }
        }

        //6:保存完文章想kafka 发送一个文章的id
        kafkaTemplate.send("wemediazidongshenhe", JSON.toJSONString(wmNews.getId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //提取封面图片且维护封面和素材表之间的关系
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> imageList, WmNews wmNews) {
        //1:判断多图 一图 修改主表字段
        List<String> imageListNew = dto.getImages();
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)) {
            if (imageList.size() > 0 && imageList.size() <= 2) {
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                imageListNew = imageList.stream().limit(1).collect(Collectors.toList());
            } else if (imageList.size() > 2) {
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                imageListNew = imageList.stream().limit(3).collect(Collectors.toList());
            } else {
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }
        String imageStr = null;
        if (imageListNew.size() > 0) {
            imageStr = imageListNew.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", "");

            wmNews.setImages(imageStr);
        }
        this.updateById(wmNews);

        //2:维护封面图片和素材的关系
        List<String> imageListNew1 = new ArrayList<>();
        for (String s : imageListNew) {
            imageListNew1.add(s.replace(fileServerUrl, ""));
        }
        ResponseResult responseResult = this.saveRelativeInfoForContent(imageListNew1, wmNews.getId());
        return responseResult;
    }

    //保存素材关系表
    private ResponseResult saveRelativeInfoForContent(List<String> imageList, Integer wmNewsId) {
        //1:判断提取出来的图片是否存在与素材库中
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, imageList);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId, user.getId());
        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(lambdaQueryWrapper);

        //2:如果存在，二次过滤真实存在与素材库的图片提取，存新的List《String》
        List<String> wmMaterialListNew = new ArrayList<>();
        if (wmMaterialList.size() > 0) {
            //3: 给每条数据构建模型，map集合 key==url  value==素材id
            Map<String, Integer> map = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            //4: 循环wmMaterialList 过滤摸鱼的
            for (String s : imageList) {
                Integer wmId = map.get(s);
                if (wmId == null) {
                    //这是个摸鱼 库中没有的
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                } else {
                    wmMaterialListNew.add(wmId.toString());
                }
            }
        }
        //5:保存中间表
        wmNewsMaterialMapper.saveRelationsByContent(wmMaterialListNew, wmNewsId, WM_NEWS_CONTENT_REFERENCE);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //自定义提取文章内容中的图片
    private List<String> ectractUrlInfo(List<Map> mapList) {
        List<String> imageList = new ArrayList<>();
        for (Map map : mapList) {
            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)) {
                String imageUrl = (String) map.get("value");
                imageList.add(imageUrl.replace(fileServerUrl, ""));
            }
        }
        return imageList;
    }

    @Override
    public ResponseResult findByNewId(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult deleteByNewId(Integer id) {

        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //文章状态 9 && 上架1 不能删
        if (wmNews.getStatus().equals(9) && wmNews.getEnable() == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //删除中间表
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        //删除主表
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //校验只能是已发布的才能上下架
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        if (dto.getEnable() != null && (dto.getEnable() == 1 || dto.getEnable() == 0)) {
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()));

            //发kafka消息  通知文章服务上下架文章   生产者   文章微服务消费者
            Map<String, Object> map = new HashMap<>();
            map.put("enable", dto.getEnable()); //0；上架  1：下架
            map.put("articleId", wmNews.getArticleId());
            kafkaTemplate.send("newsDownOrUp", JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateNewStatus(WmNews wmNews) {
        if (wmNews == null && wmNews.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean b = this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getStatus, wmNews.getStatus())
                .set(WmNews::getArticleId, wmNews.getArticleId())
                .set(WmNews::getReason, wmNews.getReason())
                .eq(WmNews::getId, wmNews.getId()));
        //boolean b = this.updateById(wmNews);
        if (b) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public List<Integer> findNews() {

        //查询审核通过待发布状态 8  发布时间 < 当前时间
        List<WmNews> wmNewsList = wmNewsMapper.selectList(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8)
                .lt(WmNews::getPublishTime, new Date()));

        //list《对象》--》list《newsId》
        List<Integer> list = wmNewsList.stream().map(WmNews::getId).collect(Collectors.toList());

        return list;
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {

        //1：mybatis 原生写法分页查询文章状态为3文章
        dto.checkParam();
        //1 0； 2 10；3 20  (当前页-1)*每页条数
        dto.setPage((dto.getPage() - 1) * dto.getSize());

        List<WmNewsVo> newsVoList = wmNewsMapper.findList(dto);
        int count = wmNewsMapper.findCount(dto);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(newsVoList);
        return responseResult;
    }

    @Override
    public WmNewsVo findNewsById(Integer id) {
        if (id == null) {
            return null;
        }

        //查wmnews
        WmNews wmNews = this.getById(id);
        WmUser wmUser = null;
        if (wmNews != null && wmNews.getUserId() != null) {

            //查userid 作者
            wmUser = wmUserService.getById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());

        return wmNewsVo;
    }

}
